import React, { useEffect, useState } from 'react';
import { Space, Modal, message } from 'antd';
import { connect, Dispatch, history, Location } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import ProCard from '@ant-design/pro-card';
import { CQ_DOC_INIT, FILL_CQ_DOC } from '@/actions/workbench';
import { ConnectState } from '@/models/connect';
import { AppItem } from '@/types/app';
import { DataItem } from '@/types/global';
import { UndoFillInfoTaskState, CqBaseInfoFormValue, CqDetailInfoFormValue,
  CqDocInfoFormValue, CqDocInfoRecord, CqUndoTaskType } from '@/types/workbench';
import { EMPTY_CQ_UNDO_TASK, EMPTY_CQ_BASE_INFO, EMPTY_CQ_DETAIL_INFO, EMPTY_CQ_DOC_INFO } from './common';
import { CqBaseInfoForm, CqDetailInfoForm, CqDocInfoForm } from './components';

interface FillCqDocInfoProps {
  dispatch: Dispatch;
  location: Location;
  auditorData: DataItem[];
  designerData: DataItem[];
  loading: boolean;
  systemData: DataItem[];
  clusterData: DataItem[];
  appList: AppItem[];
}

/**
 * 录入需求文档信息
 */
const FillCqDocInfo: React.FC<FillCqDocInfoProps> = (props) => {
  // 当前表单信息
  const [formData, setFormData] = useState<CqUndoTaskType>(EMPTY_CQ_UNDO_TASK);
  const [baseInfo, setBaseInfo] = useState<CqBaseInfoFormValue>(EMPTY_CQ_BASE_INFO);
  const [detailInfo, setDetailInfo] = useState<CqDetailInfoFormValue>(EMPTY_CQ_DETAIL_INFO);
  const [docInfo, setDocInfo] = useState<CqDocInfoFormValue>(EMPTY_CQ_DOC_INFO);

  useEffect(() => {
    console.log('FillCqDocInfo.useEffect');
    // 获取页面传值
    const { location } = props;
    const { state } = location as { state: UndoFillInfoTaskState };
    // 未传值，直接返回登录
    if (!state) {
      goLogin();
      return;
    }
    const cqUndoTaskInfo = state && state.cqUndoTaskInfo;
    const cqDetailInfo = state && state.cqDetailInfo;
    if (cqUndoTaskInfo && cqDetailInfo) {
      // 满足条件，开始查询页面参数
      const { dispatch } = props;
      dispatch(CQ_DOC_INIT({}));
      const { cqCode, cqName, systemCode, clstCode, appCode } = cqUndoTaskInfo;
      const { auditor, designerA, designerB, devStartDate, devEndDate, sitStartDate, sitEndDate,
        uatStartDate, uatEndDate, prdDate } = cqDetailInfo;
      const baseInfo: CqBaseInfoFormValue = {
        cqCode,
        cqName,
        systemCode,
        clstCode,
        appCode,
        auditor
      };
      const detailInfo: CqDetailInfoFormValue = {
        cqCode,
        designerA,
        designerB,
        devStartDate,
        devEndDate,
        sitStartDate,
        sitEndDate,
        uatStartDate,
        uatEndDate,
        prdDate
      };
      setBaseInfo(baseInfo);
      setFormData(cqUndoTaskInfo);
      setDetailInfo(detailInfo);
    } else {
      Modal.warn({
        title: '警告',
        content: '非法访问，请检查数据',
        okText: '确定',
        onOk: () => goBack()
      });
    }
  }, []);

  const goLogin = () => {
    message.warning('不允许直接访问，请通过我的待办交易进入');
    history.replace('/user/login');
  }

  /**
   * 退出按钮
   */
  const goBack = () => {
    history.goBack();
  }

  const handleSubmit = (record: CqDocInfoFormValue) => {
    console.log('Received values of form: ', record);
    // const queryParams = props.location.query;
    fillCqDocInfo(record);
  }

  const fillCqDocInfo = async (record: CqDocInfoFormValue) => {
    // 与服务端通讯
    const { dispatch } = props;
    const { actTaskId, actInstId, cqId } = formData;
    const values: CqDocInfoRecord = {
      actTaskId,
      actInstId,
      cqId,
      ...record
    };
    // 获取当前登录用户，作为任务处理人
    const res = await dispatch(FILL_CQ_DOC({
      ...values,
    }));
    if (res) {
      // 是否重置表单
      message.success('需求文档信息录入成功', 1)
      .then(() => onExit());
    }
  }

  /**
   * 退出按钮
   */
  const onExit = () => {
    history.goBack();
  }

  const { auditorData, designerData, systemData, clusterData, appList, loading } = props;

  return (
    <PageContainer title='录入需求文档信息'>
      <Space direction='vertical' size='middle' style={{ display: 'flex' }}>
        <ProCard
          title='需求基本信息'
        >
          <CqBaseInfoForm
            colon={false}
            loading={false}
            auditorData={auditorData}
            systemData={systemData}
            clusterData={clusterData}
            appList={appList}
            formData={baseInfo}
          />
        </ProCard>
        <ProCard
          title='需求详细信息'
          collapsible
          defaultCollapsed
        >
          <CqDetailInfoForm
            colon={false}
            loading={loading}
            designerData={designerData}
            flag={'view'}
            formData={detailInfo}
          />
        </ProCard>
        <ProCard title='需求文档信息'>
          <CqDocInfoForm
            colon={false}
            loading={loading}
            formData={docInfo}
            onSubmit={handleSubmit}
            onCancel={onExit}
          />
        </ProCard>
      </Space>
    </PageContainer>
  );
}

export default connect(({ cqs, systems, users, loading }: ConnectState) => ({
  auditorData: users.auditorData,
  designerData: users.designerData,
  systemData: systems.systemData,
  clusterData: systems.clusterData,
  appList: cqs.appList,
  loading: loading.effects['workbenchs/fillCqDocInfo'] || loading.effects['workbenchs/fetchCqDocInitParams'],
}))(FillCqDocInfo);